﻿using Coravel;
using Coravel.Invocable;

namespace MyKnownTemplate.Web;

/// <summary>
/// 系统Web后端配置类。
/// </summary>
public static class AppWeb
{
    /// <summary>
    /// 添加系统应用程序。
    /// </summary>
    /// <param name="services"></param>
    /// <param name="action"></param>
    public static void AddApp(this IServiceCollection services, Action<AppInfo> action = null)
    {
        ModuleHelper.InitAppModules();
        //Stopwatcher.Enabled = true;
        services.AddMyKnownTemplate();
        services.AddMyKnownTemplateCore(action);
        services.AddMyKnownTemplateRazor();

        services.AddKnownCells();
        switch (Config.App.Type)
        {
            case AppType.Web:
                services.AddKnownWeb();
                services.AddKnownWebApi();
                break;
            case AppType.Desktop:
                services.AddKnownWin();
                break;
        }

        services.AddScheduler();
        services.AddTransient<ImportTaskJob>();
    }

    /// <summary>
    /// 使用系统Web应用程序。
    /// </summary>
    /// <param name="app"></param>
    public static void UseApp(this WebApplication app)
    {
        //使用Known框架
        app.UseKnown();
        //配置定时任务
        app.Services.UseApp();
    }

    /// <summary>
    /// 使用系统桌面应用程序。
    /// </summary>
    /// <param name="provider"></param>
    public static void UseApp(this IServiceProvider provider)
    {
        provider.UseScheduler(scheduler =>
        {
            //每5秒执行一次异步导入
            scheduler.Schedule<ImportTaskJob>().EveryFiveSeconds();
        });
    }

    private static void AddMyKnownTemplateCore(this IServiceCollection services, Action<AppInfo> action = null)
    {
        services.AddKnownCore(info =>
        {
            //info.ProductId = "Test";
            //info.CheckSystem = info => Result.Error("无效密钥，请重新授权！");
            action?.Invoke(info);
        });

        services.AddScoped<IHomeService, HomeService>();
        services.AddScoped<IApplyService, ApplyService>();

        //注册待办事项显示流程表单
        //Config.ShowMyFlow = flow =>
        //{
        //    if (flow.Flow.FlowCode == AppFlow.Apply.Code)
        //        ApplyForm.ShowMyFlow(flow);
        //};
    }
}

class ImportTaskJob : IInvocable
{
    public Task Invoke() => ImportHelper.ExecuteAsync();
}